package com.photoeditor.demo.model.store.download;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.FileUtil;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.db.ExtraBean;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterCategoryBean;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.store.module.LocalPluginUtil;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.model.store.module.StoreOnlineManager;
import com.photoeditor.demo.util.ImageCache;
import com.photoeditor.demo.util.ZipUtil;
import com.photoeditor.demo.util.store.StoreDownloadSender;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import static com.photoeditor.demo.model.store.module.LocalPluginUtil.STICKER_PLUGIN_FOLDER_PATH;

/**
 * 下载工具类，filter和详情界面共用
 */
public class DownloadUtils {

    /**
     * 下载按钮默认状态
     */
    public static final int DOWNLOAD_DEFAULT = 1;

    /**
     * 下载按钮点击- 但下载状态还是0%
     */
    public static final int DOWNLOAD_CLICK = 2;

    /**
     * 下载进行中 - 下载状态是1%  -  99%
     */
    public static final int DOWNLOAD_BING = 3;

    /**
     * 下载完成 - 下载状态是100%
     */
    public static final int DOWNLOAD_END = 4;

    /**
     * 上一次下载的时间
     */
    public static final String LAST_DOWNLOAD_TIME = "last_download_time";

    private static DownloadUtils instance;


    private DownloadUtils() {

    }

    public synchronized static DownloadUtils getInstance() {
        if (instance == null) {
            instance = new DownloadUtils();
        }
        return instance;
    }

    /**
     * 存放各个下载器
     */
    private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();

    /**
     * 包名对于显示的百分比
     */
    private Map<String, Integer> percentages = new HashMap<String, Integer>();

    private HashSet<IDownloadListener> listeners = new HashSet<IDownloadListener>();

    private void download(StoreOnlineBean bean, int type) {
        SpUtils.obtain().save(LAST_DOWNLOAD_TIME, System.currentTimeMillis());
        String pkgName = bean.getPkgName();
        if (type == BaseOnlineManager.STORE_FUNC_TYPE_FILTER) {
            if (bean.getType() == StoreOnlineBean.TYPE_CATEGORY) {
                DLog.d("wmgTest", "滤镜 category");
                if (!StoreOnlineManager.getInstance().isInstalledCategoryById(bean.getId())) {
                    String downloadUrl = bean.getDownUrl();
                    //downloadClick(contentInfoBO.getPkgname());
                    pkgName = bean.getId();
                    addDownloadStatus(pkgName, DOWNLOAD_CLICK);

                    //重置状态
                    percentages.put(pkgName, 0);

                    //点击开始下载按钮 ， 可能因为网络原因，不能立刻显示百分比， 默认先显示0%
                    onProgressUpdate(pkgName, 0);

                    String rootDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                            ComponentContext.getContext(),
                            "downloadtmp", true);

                    String name = bean.getName() + String.valueOf(System.currentTimeMillis());
                    name = ImageCache.hashKeyForDisk(name);
                    String localfile = rootDir + "/" + name + ".zip";

                    String threadcount = "1";
                    DownloadTask<StoreOnlineBean> downloadTask = new DownloadTask<StoreOnlineBean>(bean, type);
                    downloadTask.execute(downloadUrl, localfile, threadcount);
                }
            } else if (bean.getType() == StoreOnlineBean.TYPE_ITEM || bean.getType() == FilterConstant.TYPE_ARTISTIC) {
                DLog.d("wmgTest", "滤镜 item");
                int downloadStatus = getDownloadStatus(pkgName);
                if (StoreOnlineManager.getInstance().isInstalledByPkgName(bean, type)) {
                    // 内置情况, 或已下载为启用
                    onProgressUpdate(pkgName, 100);
                    sendDownloadFinishBroadcast(ComponentContext.getContext(), pkgName, type);

                    percentages.put(pkgName, 100);
                } else {
                    String downloadUrl = bean.getDownUrl();
                    //downloadClick(contentInfoBO.getPkgname());
                    addDownloadStatus(pkgName, DOWNLOAD_CLICK);

                    //重置状态
                    percentages.put(pkgName, 0);

                    //点击开始下载按钮 ， 可能因为网络原因，不能立刻显示百分比， 默认先显示0%
                    onProgressUpdate(pkgName, 0);
                    String rootDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                            ComponentContext.getContext(),
                            "filterzip");

                    final String name = ImageCache.hashKeyForDisk(bean.getName());
                    String localfile = rootDir + "/" + name + ".zip";
                    String threadcount = "1";
                    DownloadTask<StoreOnlineBean> downloadTask = new DownloadTask<StoreOnlineBean>(bean, type);
                    downloadTask.execute(downloadUrl, localfile, threadcount);
                }
            }
        } else if (type == BaseOnlineManager.STORE_FUNC_TYPE_STICKER) {
            if (LocalPluginUtil.isInsidePkg(pkgName) && LocalPluginUtil.copyInsideFileToExternalPath(pkgName)) {
                ExtraBean extraBean = StoreOnlineManager.toExtraBean(bean
                        , LocalPluginUtil.generateLocalFilePath(STICKER_PLUGIN_FOLDER_PATH, pkgName));
                //下载完成， 添加到local滤镜里
                DataManager.getInstance().insertOrUpdateSticker(extraBean);
                onProgressUpdate(pkgName, 100);
                sendDownloadFinishBroadcast(ComponentContext.getContext(), pkgName, type);
                percentages.put(pkgName, 100);
            } else if (StoreOnlineManager.getInstance().isInstalledByPkgName(bean, type)) {
                // 已下载为启用
                onProgressUpdate(pkgName, 100);
                percentages.put(pkgName, 100);
                sendDownloadFinishBroadcast(ComponentContext.getContext(), pkgName, type);
            } else {
                String downloadUrl = bean.getDownUrl();
                //downloadClick(contentInfoBO.getPkgname());
                addDownloadStatus(pkgName, DOWNLOAD_CLICK);

                //重置状态
                percentages.put(pkgName, 0);

                //点击开始下载按钮 ， 可能因为网络原因，不能立刻显示百分比， 默认先显示0%
                onProgressUpdate(pkgName, 0);
                String localfile = LocalPluginUtil.generateLocalFilePath(STICKER_PLUGIN_FOLDER_PATH, pkgName);
                String threadcount = "1";
                DownloadTask<StoreOnlineBean> downloadTask = new DownloadTask<>(bean, type);
                downloadTask.execute(downloadUrl, localfile, threadcount);
            }
        } else if (type == BaseOnlineManager.NORMAL_RESOURCE_FILE) {
            String name = bean.getPkgName();
            boolean isInstalled = DataManager.getInstance().isExistNormalResFile(name);
            if (isInstalled) {
                sendDownloadFinishBroadcast(ComponentContext.getContext(), name, type);
                return;
            }
            String downloadUrl = bean.getDownUrl();
            addDownloadStatus(name, DOWNLOAD_CLICK);
            //重置状态
            percentages.put(name, 0);
            //点击开始下载按钮 ， 可能因为网络原因，不能立刻显示百分比， 默认先显示0%
            onProgressUpdate(name, 0);
            String rootDir = DataManager.NORMAL_RES_DIR;
            String fileName = rootDir + bean.getPkgName() + "tmp";
            String threadcount = "1";
            DownloadTask<StoreOnlineBean> downloadTask = new DownloadTask<StoreOnlineBean>(bean, type);
            downloadTask.execute(downloadUrl, fileName, threadcount);
        }

    }


    /**
     * 响应开始下载按钮的点击事件
     * chenfangyi修改:将内置的下载放置到这里, 不需要特殊处理
     *
     * @param data
     * @param type {@link com.photoeditor.demo.model.store.module.BaseOnlineManager#STORE_FUNC_TYPE_FILTER}
     */
    public synchronized void startDownload(Serializable data, int type) {
        //sdcard是否存在
        if (com.photoeditor.demo.util.FileUtil.isSDCardMounted()) {
            if (data instanceof StoreOnlineBean) {
                StoreOnlineBean bean = (StoreOnlineBean) data;
                download(bean, type);
            }
        } else {
            Toast.makeText(ComponentContext.getContext(), "sdcard error ", Toast.LENGTH_LONG).show();
        }
    }

    ;

    /**
     * 下载状态
     */
    private Map<String, Integer> mDownloadStatus = new HashMap<String, Integer>();

    public Map<String, Integer> getDownloadStatus() {
        return mDownloadStatus;
    }

    public synchronized void downloadStatus(String packageName, int downloadS) {
        if (mDownloadStatus.get(packageName) != null) {
            mDownloadStatus.put(packageName, downloadS);
        }
    }

    /**
     * 增加
     *
     * @param packageName
     * @param downloadS
     */
    public synchronized void addDownloadStatus(String packageName, int downloadS) {
        mDownloadStatus.put(packageName, downloadS);
    }

    /**
     * 清空下载状态
     */
    public synchronized void clearDownloadStatus() {
        mDownloadStatus.clear();
        downloaders.clear();
        listeners.clear();
    }

    /**
     * 退出时停止下载
     * 清除所有下载器和监听器还有状态  防止内存泄漏
     * 在ondestory时记得调用!!!
     */
    public synchronized void stopDownload() {
        clearListeners();
        mDownloadStatus.clear();//清除所有的下载记录
        resetPercentage();
        //停止下载
        Iterator ite = downloaders.entrySet().iterator();
        while (ite.hasNext()) {
            Entry<Object, Object> entry = (Entry<Object, Object>) ite.next();
            Downloader downloader = (Downloader) entry.getValue();//上面key对应的value
            downloader.pause();
        }
        downloaders.clear();
    }

    /**
     * 移除所以下载这个包的信息, 以便下次能正常下载
     *
     * @param packageName
     * @param downUrl
     */
    public synchronized void removeDownloadMark(String packageName, String downUrl) {
        mDownloadStatus.remove(packageName);
        percentages.remove(packageName);
        //停止下载 并移除下载器
        Downloader downloader = downloaders.remove(downUrl);
        if (downloader != null) {
            downloader.pause();
        }
    }

    /**
     * 获取下载状态
     *
     * @param packageName
     * @return
     */
    public synchronized int getDownloadStatus(String packageName) {
        if (packageName == null) {
            return DOWNLOAD_DEFAULT;
        }

        Integer status = mDownloadStatus.get(packageName);
        //为空是第一次点击
        if (status == null) {
            status = DOWNLOAD_DEFAULT;
        }

        return status.intValue();
    }


    /**
     * 利用消息处理机制适时更新进度条
     */
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {

                Bundle bundle = msg.getData();
                int type = bundle.getInt("type");
                String downloadUrl = bundle.getString("downloadUrl");
                //保存apk到本地sdcard地址
                final String localFile = bundle.getString("localFile");
                //下载完成大小
                int completeSize = bundle.getInt("compeleteSize");
                //总大小
                int fileSize = bundle.getInt("fileSize");
                Serializable data = bundle.getSerializable("contentInfoBO");
                if (data instanceof StoreOnlineBean) {
                    final StoreOnlineBean storeOnlineBean = (StoreOnlineBean) data;
                    String packageName = "";
                    if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_ITEM) {
                        packageName = storeOnlineBean.getPkgName();
                    } else if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_CATEGORY) {
                        packageName = storeOnlineBean.getId();
                    }
                    if (TextUtils.isEmpty(packageName)) {
                        packageName = storeOnlineBean.getPkgName();
                    }
                    if (fileSize <= 0 || TextUtils.isEmpty(packageName)) {
                        return;
                    }

                    if (completeSize >= fileSize) {
                        if (downloaders.get(downloadUrl) != null) {
                            downloaders.get(downloadUrl).reset();
                        }
                        downloaders.remove(downloadUrl);
                        if (type == BaseOnlineManager.STORE_FUNC_TYPE_FILTER) {
                            if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_ITEM ||
                                    storeOnlineBean.getType() == FilterConstant.TYPE_ARTISTIC) {
                                ThreadPool.runOnNonUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handleFilterItemDownloadFinish(localFile, storeOnlineBean);
                                    }
                                });
                            } else if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_CATEGORY) {
                                // 滤镜分类压缩包下载完，需要解压后，再处理
                                ThreadPool.runOnNonUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        handleFilterCategoryDownloadFinish(localFile, storeOnlineBean);
                                    }
                                });
                            }
                        } else if (type == BaseOnlineManager.STORE_FUNC_TYPE_STICKER) {
                            ExtraBean extraBean = StoreOnlineManager.toExtraBean(storeOnlineBean, localFile);
                            //下载完成， 添加到local滤镜里
                            DataManager.getInstance().insertOrUpdateSticker(extraBean);
                            sendDownloadFinishBroadcast(ComponentContext.getContext(), packageName, type);
                            percentages.put(packageName, 100);
                            onProgressUpdate(packageName, 100);
                            removeDownloadMark(packageName, storeOnlineBean.getDownUrl());
                        }  else if (type == BaseOnlineManager.NORMAL_RESOURCE_FILE) {
                            //下载完成，重命名
                            try {
                                FileUtil.copyFile(localFile, localFile.substring(0, localFile.length() - 3), true);
                                FileUtil.delete(new File(localFile));
                                sendDownloadFinishBroadcast(ComponentContext.getContext(), packageName, type);
                                percentages.put(packageName, 100);
                                onProgressUpdate(packageName, 100);
                                removeDownloadMark(packageName, storeOnlineBean.getDownUrl());
                            } catch (Exception e) {
                            }
                        }
                    } else {
                        showProgress(fileSize, completeSize, packageName, type);
                    }
                }
            } else if (msg.what == 2) {//下载失败
                Bundle bundle = msg.getData();
                if (bundle != null) {
                    Serializable data = bundle.getSerializable("contentInfoBO");
                    if (data != null) {
                        String packageName = "";
                        String downUrl = "";
                        if (data instanceof StoreOnlineBean) {
                            StoreOnlineBean bean = (StoreOnlineBean) data;
                            int type = bundle.getInt("type");
                            {
                                if (bean.getType() == StoreOnlineBean.TYPE_ITEM) {
                                    packageName = bean.getPkgName();
                                } else if (bean.getType() == StoreOnlineBean.TYPE_CATEGORY) {
                                    packageName = bean.getId();
                                }
                                if (TextUtils.isEmpty(packageName)) {
                                    packageName = bean.getPkgName();
                                }
                            }
                            downUrl = bean.getDownUrl();
                        }
                        if (!TextUtils.isEmpty(packageName)) {//先移除掉下载的状态然后回调失败
                            removeDownloadMark(packageName, downUrl);
                            onFailed(packageName);
                        }
                    }
                }
            }
        }
    };

    private void handleFilterItemDownloadFinish(String localFilePath, final StoreOnlineBean storeOnlineBean) {
        String packageName = storeOnlineBean.getPkgName();

        if (!DataManager.getInstance().isExistFilterCategory(storeOnlineBean.getCategoryId())) {
            StoreOnlineBean categoryOnlineBean = StoreOnlineManager.getInstance().getFilterCategoryBeanByItem(storeOnlineBean);
            FilterCategoryBean categoryBean = StoreOnlineManager.toFilterCategoryBean(categoryOnlineBean);

            // 分类图片取第一个滤镜图片
            ArrayList<StoreOnlineBean> child = categoryOnlineBean.getChildModules();
            categoryBean.setIconUrl(child.get(0).getIcon());
            categoryBean.setFirstFilterId(String.valueOf(child.get(0).getPkgName()));
            DataManager.getInstance().insertFilterCategory(categoryBean);
        }

        FilterBean filterBean = null;
        if (storeOnlineBean.getType() == FilterConstant.TYPE_ARTISTIC) {
            String artFilterDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                    ComponentContext.getContext(),
                    "artfilter", true);
            //如果是艺术滤镜，还要进一步解压
            unzipArtFilterSource(localFilePath, storeOnlineBean.getPkgName());
            filterBean = StoreOnlineManager.toFilterBean(storeOnlineBean, artFilterDir + File.separator + storeOnlineBean.getPkgName() + ".zip");
        } else {
            filterBean = StoreOnlineManager.toFilterBean(storeOnlineBean, localFilePath);
        }

        ArrayList<FilterBean> filterBeans = new ArrayList<>();
        filterBeans.add(filterBean);
        //下载完成， 添加到local滤镜里
        DataManager.getInstance().insertFilters(filterBeans);
        sendDownloadFinishBroadcast(ComponentContext.getContext(), packageName, BaseOnlineManager.STORE_FUNC_TYPE_FILTER);


        percentages.put(packageName, 100);
        onProgressUpdate(packageName, 100);
        removeDownloadMark(packageName, storeOnlineBean.getDownUrl());
    }

    public void handleFilterCategoryDownloadFinish(String localFilePath, final StoreOnlineBean storeOnlineBean) {
        // 解压到指定目录
        String rootDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                ComponentContext.getContext(),
                "filterzip", true);
        String artFilterDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                ComponentContext.getContext(),
                "artfilter", true);
        File file = new File(localFilePath);
        final String packageName = storeOnlineBean.getId();
        String downUrl = storeOnlineBean.getDownUrl();
        ArrayList<String> fileList = null;
        if (file.exists()) {
            try {
                fileList = ZipUtil.getEntriesNames(file);
                ZipUtil.upZipFile(file, rootDir);
                // 解压后，删除原文件
                file.delete();
            } catch (Exception e) {
                // 解压失败，通知下载失败
                if (!TextUtils.isEmpty(packageName)) {//先移除掉下载的状态然后回调失败
                    removeDownloadMark(packageName, downUrl);
                    onFailed(packageName);
                }
                e.printStackTrace();
                return;
            }
        }
        // 解压后，插入分类及滤镜
        FilterCategoryBean categoryBean = StoreOnlineManager.toFilterCategoryBean(storeOnlineBean);
        ArrayList<StoreOnlineBean> child = storeOnlineBean.getChildModules();
        if (child != null && child.size() > 0 && fileList != null && fileList.size() > 0) {
            ArrayList<FilterBean> childFilter = new ArrayList<>(child.size());
            for (StoreOnlineBean bean : child) {
                String fileName = null;
                for (String tmp : fileList) {
                    if (tmp.startsWith(bean.getPkgName())) {
                        fileName = tmp;
                        break;
                    }
                }
                if (!TextUtils.isEmpty(fileName)) {
//                    if (bean != null && bean.getType() == FilterConstant.TYPE_ARTISTIC) {
//                        //如果是艺术滤镜，还要进一步解压
//                        unzipArtFilterSource(rootDir + File.separator + fileName, bean.getPkgName());
//                        DLog.d("wmgTest", "艺术滤镜，进一步解压");
//                        FilterBean filterBean = StoreOnlineManager.toFilterBean(bean, artFilterDir + File.separator + fileName);
//                        childFilter.add(filterBean);
//                    } else {
                    FilterBean filterBean = StoreOnlineManager.toFilterBean(bean, rootDir + File.separator + fileName);
                    childFilter.add(filterBean);
//                    }
                }
            }
            if (childFilter.size() > 0) {
                // 分类图片取第一个滤镜图片
                categoryBean.setIconUrl(childFilter.get(0).getIcon());
                categoryBean.setFirstFilterId(String.valueOf(childFilter.get(0).getPackageName()));
                if (storeOnlineBean.isBuy() && storeOnlineBean.isLockMain()) {
                    DataManager.getInstance().insertFilterCategory(categoryBean, storeOnlineBean.getLockPosition());
                } else {
                    DataManager.getInstance().insertFilterCategory(categoryBean);
                }
                DataManager.getInstance().insertFilters(childFilter);
            }
        }
        sendDownloadFinishBroadcast(ComponentContext.getContext(), packageName, BaseOnlineManager.STORE_FUNC_TYPE_FILTER);
        percentages.put(packageName, 100);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                onProgressUpdate(packageName, 100);
            }
        });
        removeDownloadMark(packageName, storeOnlineBean.getDownUrl());
    }

    private void unzipArtFilterSource(String zipPath, String pkgName) {
        if (TextUtils.isEmpty(zipPath)) {
            return;
        }
        try {
            File sourceFile = new File(zipPath);

            String externalArtFilterDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                    ComponentContext.getContext(),
                    "artfilter", true);
            File targetFile = new File(externalArtFilterDir + File.separator + pkgName + ".zip");
            DLog.d("wmgTest", "copy target " + targetFile.getAbsolutePath());
            //拷贝该zip到sd卡下filterzip目录下
            com.photoeditor.demo.util.FileUtil.copyFile(sourceFile, targetFile);
            //解压该zip文件到sd卡下artfilter目录下
            ZipUtil.upZipFile(sourceFile, externalArtFilterDir + File.separator + pkgName);
            //删除原zip文件
            sourceFile.delete();

            //逐个解压并删除
//            File artFileZipDir = new File(externalArtFilterDir);
//            String dir = artFileZipDir.getPath();
//            String[] files = artFileZipDir.list();
//
//            if (files == null || files.length == 0) {
//                return;
//            }
//            for (String fileName: files) {
//                File file = new File(dir + File.separator + fileName);
//                int lastDotIndex = fileName.lastIndexOf(".");
//                String dirName = fileName.substring(0, lastDotIndex);
//                //解压该zip文件到sd卡下artfilter目录下
//                ZipUtil.upZipFile(file, externalArtFilterDir + File.separator + dirName);
//                //删除该文件
//                file.delete();
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送下载完成广播
     *
     * @param context
     * @param packageName
     */
    public synchronized void sendDownloadFinishBroadcast(Context context, String packageName, int type) {
        StoreDownloadSender.sendDownOverBrocast(context, packageName, type);
    }


    /**
     * 显示进度条
     *
     * @param fSize       文件总大小
     * @param complete    下载完成大小
     * @param packageName
     * @param type        1列表、  2详情
     */
    public synchronized void showProgress(int fSize, int complete, String packageName, int type) {
        //文件总大小
        double fileSize = (double) fSize;
        //下载完成
        int downloadComplete = complete;
        DecimalFormat df = new DecimalFormat("0.00", new DecimalFormatSymbols(new Locale("en", "US")));

        //截取小数点后2位
        String resultDF = df.format(downloadComplete / fileSize);
        double resultDouble = Double.parseDouble(resultDF);
        //转换为百分比, 实际没有到达100%
        int resultInt = (int) (resultDouble * 100);
        if (resultInt == 100) {
            resultInt = 99;
        }
        onProgressUpdate(packageName, resultInt);

        if (percentages.get(packageName) != null) {
            percentages.put(packageName, resultInt);
        }

        downloadStatus(packageName, DOWNLOAD_BING);
    }

    public synchronized void onProgressUpdate(String packageName, int progress) {
        List<IDownloadListener> removeListeners = new ArrayList<>();
        for (IDownloadListener listener : listeners) {
            String pName = listener.getDownloadId();
            if (pName != null && pName.equals(packageName)) {
                listener.onProgressUpdate(packageName, progress);
                if (progress == 100) {
                    removeListeners.add(listener);
                }
            }
        }
        listeners.removeAll(removeListeners);
    }

    public synchronized void onFailed(String packageName) {
        List<IDownloadListener> removeListeners = new ArrayList<>();
        for (IDownloadListener listener : listeners) {
            String pName = listener.getDownloadId();
            if (pName != null && pName.equals(packageName)) {
                listener.onFailed(packageName);
                removeListeners.add(listener);
            }
        }
        // 下载失败不应该主动清除监听，因为外部可能会再次触发下载，而没有重新设置新的监听进来导致不能更新进度
        // listeners.removeAll(removeListeners);
    }

    /**
     * 返回对应滤镜下载百分率
     *
     * @param packageName
     * @return
     */
    public synchronized Integer getPercentage(String packageName) {
        //为空是第一次点击
        if (packageName == null) {
            return 0;
        }

        if (percentages.get(packageName) == null) {
            return 0;
        }

        return percentages.get(packageName);
    }

    public synchronized void resetPercentage() {
        if (percentages != null) {
            percentages.clear();
        }
    }

    /**
     * 本地删除滤镜后， 重置状态
     *
     * @param packageName
     */
    public synchronized void setPercentage(String packageName, int percentage) {
        percentages.put(packageName, percentage);
    }

    /**
     * 添加下载监听器
     *
     * @param listener
     */
    public synchronized void addListener(IDownloadListener listener) {
        listeners.add(listener);
    }

    /**
     * 移除下载监听器
     *
     * @param listener
     */
    public synchronized void removeListener(IDownloadListener listener) {
        if (listener == null) {
            return;
        }
        listeners.remove(listener);
    }

    /**
     * 清除监听器
     */
    public synchronized void clearListeners() {
        listeners.clear();
    }

    /**
     * 获取或创建下载器
     *
     * @param url
     * @param localfile
     * @param threadcount
     * @param contentInfoBO
     * @param type
     * @return
     */
    public synchronized Downloader getOrCreateDownloader(String url, String localfile,
                                                         int threadcount, Serializable contentInfoBO, int type) {
        Downloader downloader = null;
        if (downloaders.containsKey(url)) {
            downloader = downloaders.get(url);
        } else {
            downloader = new Downloader(url, localfile, threadcount, ComponentContext.getContext(), mHandler,
                    contentInfoBO, type);
            downloaders.put(url, downloader);
        }
        return downloader;
    }
}
